package com.sxt.demo.djiapplication.dji

import android.content.Context
import android.graphics.SurfaceTexture
import android.view.TextureView
import com.sxt.demo.djiapplication.utils.ToastUtils
import dji.common.product.Model
import dji.sdk.base.BaseProduct
import dji.sdk.camera.VideoFeeder
import dji.sdk.codec.DJICodecManager

class CaptureOperator(

    /**
     * 上下文
     */
    private val context: Context,

    /**
     * 产品
     */
    private val product: BaseProduct,

    /**
     * 视频预览view
     */
    private val videoSurface: TextureView
) : TextureView.SurfaceTextureListener {

    private var codecManager: DJICodecManager? = null

    /**
     * The callback for receiving the raw H264 video data for camera live view
     */
    private val receiveVideoDataListener: VideoFeeder.VideoDataListener =
        VideoFeeder.VideoDataListener { videoBuffer, size ->
            codecManager?.sendDataToDecoder(
                videoBuffer,
                size
            )
        }

    /**
     * 初始化相机捕捉
     */
    fun initCapture() {
        if (product.isConnected) {
            videoSurface.surfaceTextureListener = this
            if (product.model != Model.UNKNOWN_AIRCRAFT) {
                VideoFeeder.getInstance().primaryVideoFeed.addVideoDataListener(
                    receiveVideoDataListener
                )
            }
        } else {
            ToastUtils.show(context, "产品未连接")
        }
    }

    /**
     * 销毁相机捕捉
     */
    fun destroyCapture() {
        product.camera?.let {
            VideoFeeder.getInstance().primaryVideoFeed.addVideoDataListener { _, _ -> }
        }
    }

    /*===============================SurfaceTexture监听器==========================================*/
    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
        if (codecManager == null) {
            codecManager = DJICodecManager(context, surface, width, height)
        }
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {

    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        codecManager?.let {
            it.cleanSurface()
            codecManager == null
        }
        return false
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {

    }

}